package com.cyh.core.framework.common.utils;

import java.io.*;
import java.util.Base64;

import com.cyh.core.login.entity.User;

import org.apache.poi.ss.formula.functions.T;

/**
 * @Author: yanhang_chen
 * @Date: 2020-09-21 11:47:53
 */
public class SerializeUtil {

    /**
     * 对象转base64字串
     * @param obj
     * @return
     */
    public static String toBase64String(Object obj){
        byte[] b = toByteArray (obj);
        return Base64.getEncoder().encodeToString(b);
    }

    /**
     * base64字串转对象
     * @param base64str
     * @return
     */
    public static Object toObject (String base64str) {
       return toObject(Base64.getDecoder().decode(base64str));
    }

    /**
     * 对象转数组
     * @param obj
     * @return
     */
    public static byte[] toByteArray (Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 数组转对象
     * @param bytes
     * @return
     */
    public static Object toObject (byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
            ObjectInputStream ois = new ObjectInputStream (bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }

}
